package com.echo.code.thread.lock.helper.impl;

import com.echo.code.thread.lock.Lock;
import com.echo.code.thread.lock.helper.ReadWriteLockHelper;
import com.echo.code.thread.lock.impl.ReadLock;
import com.echo.code.thread.lock.impl.WriteLock;

/**
 * ReadWriteLockHelperImpl Created by baiyap on 2018/9/24.
 */
public class ReadWriteLockHelperImpl implements ReadWriteLockHelper {

  private int writingWriters = 0;

  private int waitingWriters = 0;

  private int readingReaders = 0;

  // -----read and write switch----
  private boolean preferWriter = Boolean.TRUE;
  // ------------------------------

  @Override
  public Lock readLock() {
    return new ReadLock(this);
  }

  @Override
  public Lock writeLock() {
    return new WriteLock(this);
  }

  @Override
  public int getWritingWriters() {
    return writingWriters;
  }

  @Override
  public int getWaitingWriters() {
    return waitingWriters;
  }

  @Override
  public int getReadingReaders() {
    return readingReaders;
  }

  public ReadWriteLockHelper getMutex() {
    return this;
  }

  public boolean isPreferWriter() {
    return preferWriter;
  }

  public void changePreferWriter(boolean preferWriter) {
    this.preferWriter = preferWriter;
  }

  public void incrementWritingWriters() {
    writingWriters++;
  }

  public void decrementWritingWriters() {
    writingWriters--;
  }

  public void incrementWaitingWriters() {
    waitingWriters++;
  }

  public void decrementWaitingWriters() {
    waitingWriters--;
  }

  public void incrementReadingReaders() {
    readingReaders++;
  }

  public void decrementReadingReaders() {
    readingReaders--;
  }
}
